using FytSoa.Domain.Sys;
using FytSoa.Sugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using FytSoa.Common.Enum;
using MapsterMapper;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using Masuit.Tools.Linq;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Sys;

/// <summary>
/// 服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v1")]
public class SysAdvColumnService : SugarRepository<SysAdvColumn>,ISysAdvColumnService 
{
    private readonly IMapper _mapper;
    public SysAdvColumnService(IMapper mapper)
    {
        _mapper = mapper;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ApiResult<PageResult<SysAdvColumnDto>>> GetPagesAsync(PageParam param)
    {
        var where = Expressionable.Create<SysAdvColumn>();
        var (list,totalItems,totalPage) = await base.GetPageResultAsync(where.ToExpression(), param.Page, param.Limit, m => m.Id);
        var result = new PageResult<SysAdvColumnDto>()
        {
            Items = _mapper.Map<List<SysAdvColumnDto>>(list),
            TotalItems = totalItems,
            TotalPages = totalPage
        };
        return JResult<PageResult<SysAdvColumnDto>>.Success(result);
    }

    /// <summary>
    /// 查询所有
    /// </summary>
    /// <returns></returns>
    public async Task<ApiResult<List<SysAdvColumnDto>>> GetListAsync(WhereParam param)
    {
        var where = Expressionable.Create<SysAdvColumn>();
        var list = await base.GetListAsync(where.ToExpression(), m => m.Sort,OrderEnum.Asc);
        return JResult<List<SysAdvColumnDto>>.Success(_mapper.Map<List<SysAdvColumnDto>>(list));
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ApiResult<SysAdvColumnDto>> GetAsync(long id)
    {
        return JResult<SysAdvColumnDto>.Success(_mapper.Map<SysAdvColumnDto>(await base.GetByIdAsync(id)));
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<ApiResult<bool>> AddAsync(SysAdvColumnDto model)
    {
        model.Id = Unique.Id();
        if (model.ParentIdList.All(m => m != "0"))
        {
            model.ParentId = long.Parse(model.ParentIdList.Last());
            var paramModel = await base.GetByIdAsync(model.ParentId);
            model.Layer = paramModel.Layer + 1;
            model.ParentIdList.Add(model.Id.ToString());
        }
        else
        {
            model.ParentIdList=new List<string> {model.Id.ToString()};
        }
        
        var upModel = await base.GetFirstAsync(m => true, m => m.Sort);
        model.Sort = upModel.Sort + 1;
        return JResult<bool>.Success(await base.InsertAsync(_mapper.Map<SysAdvColumn>(model)));
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<ApiResult<bool>> ModifyAsync(SysAdvColumnDto model)
    {
        if (model.ParentIdList.All(m => m != "0"))
        {
            model.ParentId = long.Parse(model.ParentIdList.Last());
            model.ParentIdList.Add(model.Id.ToString());
        }
        else
        {
            model.ParentIdList=new List<string> {model.Id.ToString()};
        }
        return JResult<bool>.Success(await base.UpdateAsync(_mapper.Map<SysAdvColumn>(model)));
    }

    /// <summary>
    /// 删除,支持多个
    /// </summary>
    /// <param name="ids">逗号分隔</param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<ApiResult<bool>> DeleteAsync(string ids)
    {
        return JResult<bool>.Success(await base.DeleteAsync(m=>ids.StrToListLong().Contains(m.Id)));
    }

    /// <summary>
    /// 自定义排序
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ApiResult<int>> ColSort(SortParam param)
    {
        int a = 0, b = 0, c = 0;
            var list = await base.GetListAsync(m => m.ParentId == param.Parent, m => m.Sort, Common.Enum.OrderEnum.Asc);
            if (list.Count <= 0) return JResult<int>.Success();
            var index = 0;
            foreach (var item in list)
            {
                index++;
                if (index == 1)
                {
                    if (item.Id != param.Id) continue;
                    if (param.Type != 1) continue;
                    a = item.Sort;
                    b = list[index].Sort;
                    c = a;
                    a = b;
                    b = c;
                    item.Sort = a;
                    await base.UpdateAsync(item);
                    var nitem = list[index];
                    nitem.Sort = b;
                    await base.UpdateAsync(nitem);
                    break;
                }
                if (index == list.Count)
                {
                    if (item.Id != param.Id) continue;
                    if (param.Type != 0) continue;
                    a = item.Sort;
                    b = list[index - 2].Sort;
                    c = a;
                    a = b;
                    b = c;
                    item.Sort = a;
                    await base.UpdateAsync(item);
                    var nitem = list[index - 2];
                    nitem.Sort = b;
                    await base.UpdateAsync(nitem);
                    break;
                }
                if (item.Id != param.Id) continue;
                if (param.Type == 1) //下降一位
                {
                    a = item.Sort;
                    b = list[index].Sort;
                    c = a;
                    a = b;
                    b = c;
                    item.Sort = a;
                    await base.UpdateAsync(item);
                    var nitem = list[index];
                    nitem.Sort = b;
                    await base.UpdateAsync(nitem);
                    break;
                }
                else
                {
                    a = item.Sort;
                    b = list[index - 2].Sort;
                    c = a;
                    a = b;
                    b = c;
                    item.Sort = a;
                    await base.UpdateAsync(item);
                    var nitem = list[index - 2];
                    nitem.Sort = b;
                    await base.UpdateAsync(nitem);
                    break;
                }
            } 
            return JResult<int>.Success();
    }
}

